using System;
using Cinemachine;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Super
{
	public class VirtualCM2DManager : BaseSingle<VirtualCM2DManager>
	{
		public bool enableDragMove = false;
		public bool enableFollow = false;
		public bool enableScale = false;

		public MouseKey mouseDragKey;
		public CinemachineVirtualCamera virtualCM;
		public Transform moveTf;

		public float moveFactor;
		public float scaleFactor;
		public Vector2 scaleRange;

		public override void OnInit()
		{
			base.OnInit();

			EventManager.Register<MouseDragGE>(OnMouseDragGE);
			EventManager.Register<MouseScrollGE>(OnMouseScroll);
		}



		public static void DragMove(MouseKey key, Vector2 scaleRange)
		{
			Ins.enableDragMove = true;
			Ins.mouseDragKey = key;
			Ins.scaleRange = scaleRange;
			
			Ins.virtualCM.Follow = Ins.moveTf;
		}

		public static void Follow(Transform target)
		{
			Ins.enableFollow = true;
			Ins.virtualCM.Follow = target;

			Ins.enableDragMove = false;
		}

		public static void Scale(bool state)
		{
			Ins.enableScale = state;
		}

		public static void CancelDrag()
		{
			Ins.enableDragMove = false;
		}

		public static void CancelFollow()
		{
			Ins.enableFollow = false;
			Ins.virtualCM.Follow = null;
		}
		
		public void LookAtPoint(Vector2 pos)
		{
			moveTf.position = new Vector3(pos.x, pos.y, moveTf.position.z);
		}

		private void OnMouseDragGE(MouseDragGE gE)
		{
			if (EventSystem.current.IsPointerOverGameObject()) return;	// 鼠标在ui上，不响应
			if (!enableDragMove || mouseDragKey != gE.key) return;
			
			float factor = virtualCM.m_Lens.OrthographicSize * 2 * moveFactor / FWConfig.bestScreenHeight;
			Vector2 offset = InputManager.Ins.mouseMoveInfo.offsetPos * factor;

			moveTf.position -= (Vector3)offset;
		}
		
		private void OnMouseScroll(MouseScrollGE gE)
		{
			if (!enableScale) return;
			float value = virtualCM.m_Lens.OrthographicSize - gE.delta.y * scaleFactor;
			value = Mathf.Clamp(value, scaleRange.x, scaleRange.y);
			virtualCM.m_Lens.OrthographicSize = value;
		}
		
		public static void Reset()
		{
			CancelDrag();
			CancelFollow();
			Scale(false);
		}

	}


}
